import { DateTime, Duration } from "luxon"


const index2text = new Map(
    [
        [1, '周一'], [2, '周二'], [3, '周三'], [4, '周四'], [5, '周五'], [6, '周六'], [7, '周日']
    ])
const text2index = new Map(
    [
        ['周一', 1], ['周二', 2], ['周三', 3], ['周四', 4], ['周五', 5], ['周六', 6], ['周日', 7]
    ]
)
export function get_data(data) {
    const date_list = get_a_week(Number(data?.['is_this_week'] ?? 1))
    const daogao_map = parse_msg(data['msg'])
    const web_data = []
    const keys_sorted = [...daogao_map.keys()].sort((v1, v2) => v1 - v2)
    for (let i = 0; i < keys_sorted.length; i++) {
        let key = keys_sorted[i]
        const daogao_item = daogao_map.get(key)
        if (daogao_item) {
            let date_info = fmt_date(date_list[key - 1])
            web_data.push([date_info, daogao_item, ''])
        }
    }
    return web_data
}

function parse_msg(msg) {
    msg = msg.trim()
    // 效字数在3~800之间, 如果不在范围, 抛出空数据
    if (msg.length > 800 || msg < 4) return []
    const map = new Map()
    let key = 0
    let values = []
    for (let line of msg.split('\n')) {
        line = line.trim()
        if (!line) continue
        if (text2index.has(line)) {
            //读取到新key就储存上次的k: v
            if (key) {
                map.set(key, values.slice(0, 4))
                values = []
            }
            key = text2index.get(line)
        } else {
            if (line.length > 40) line = line.slice(0, 40) + '...'
            values.push(line)
        }
    }
    if (key) {
        map.set(key, values.slice(0, 4))
    }
    return map

}

function fmt_date(date) {
    return `${date.toFormat("MM'月'dd'日'")} · ${index2text.get(date.localWeekday)}`
}

function get_a_week(is_this_week = 1) {

    const now_ = DateTime.now()
    let monday = null

    if (is_this_week) {
        const days = now_.localWeekday - 1
        const dur = Duration.fromObject({ days })
        monday = now_.minus(dur)
    }
    else {
        const days = 7 - now_.localWeekday + 1
        const dur = Duration.fromObject({ days })
        monday = now_.plus(dur)
    }

    const one_day = Duration.fromObject({ days: 1 })
    const week_list = []
    for (let i = 0; i < 7; i++) {
        week_list.push(monday)
        monday = monday.plus(one_day)
    }
    return week_list
}